package com.store.practice.service.impl;

import com.store.practice.common.utils.JwtTokenUtil;
import com.store.practice.mapper.BgStaffMapper;
import com.store.practice.model.BgStaff;
import com.store.practice.model.BgStaffExample;
import com.store.practice.service.StaffUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StaffUserDetailsServiceImpl implements StaffUserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(StaffUserDetailsServiceImpl.class);
    @Autowired
    private BgStaffMapper staffMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public BgStaff getStaffByAccount(String account){
        BgStaffExample example = new BgStaffExample();
        example.createCriteria().andAccountEqualTo(account);
        List<BgStaff> staffs = staffMapper.selectByExample(example);
        if (staffs!=null||staffs.size()>0){
            return staffs.get(0);
        }
        return null;
    }

    @Override
    public Map login(String account, String password) {
        BgStaff staff = getStaffByAccount(account);
        if (staff==null){
            throw new UsernameNotFoundException("账号不存在");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(account);
        if (!passwordEncoder.matches(password,userDetails.getPassword())){
            logger.error("input password:{},userDetails password:{}",password,userDetails.getPassword());
            throw new BadCredentialsException("密码错误");
        }
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, Object> result = new HashMap<>();
        result.put("accountInfo",staff);
        result.put("token",token);
        return result;
    }
}
